var TableArticleCats = function () {
    return {
        init: function () {
			
			function restoreRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
				
				oTable.fnUpdate(aData['parentId'], nRow,0, false);
				oTable.fnUpdate(aData['catName'], nRow,1, false);
				oTable.fnUpdate(aData['catSort'], nRow,2, false);
				oTable.fnUpdate(aData['catType'], nRow,3, false);
				oTable.fnUpdate(aData['catFlag'], nRow,4, false);
				oTable.fnUpdate('<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a></a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>', nRow, 5, false);
                oTable.fnDraw();
            }
			
            function editRow(oTable, nRow,isNew) {
				var isNew=isNew?isNew:'';
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
				$.post(ajaxUrl,{ajax:''},function(idata) {
					var data = idata.data;
					var parentId = '<select name="parentId" class="sidebar-pos-option form-control input-small"><option>顶级分类</option>';
					for (var i = 0, iLen = data.length; i < iLen; i++) {
						if(aData['parentId']==data[i].catId){
							parentId +='<option value="'+data[i].catId+'" selected="selected">'+data[i].count+ data[i].catName+'</option>';
						}else{
							parentId +='<option value="'+data[i].catId+'">'+data[i].count+ data[i].catName+'</option>';
						}
					}
						parentId +='</select>';
					jqTds[0].innerHTML = parentId;
				});
				
				
				
				//jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['parentId'] + '">';
                jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['catName'] + '">';
				jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['catSort'] + '">';
				jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['catType'] + '">';
			    jqTds[5].innerHTML = '<a class="edit btn btn-xs green" href="" name="Save"><i class="fa fa-check"></i> 保存</a></a><a class="cancel btn btn-xs default" '+isNew+' href=""><i class="fa fa-times"></i> 取消</a>';
			}

            function saveRow(oTable, nRow) {
				var	jqSelects = $('select', nRow);
				oTable.fnUpdate(jqSelects[0].value, nRow, 0, false);
                var jqInputs = $('input', nRow);
                //oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
				oTable.fnUpdate(jqInputs[0].value, nRow, 1, false);
				oTable.fnUpdate(jqInputs[1].value, nRow, 2, false);
				oTable.fnUpdate(jqInputs[2].value, nRow, 3, false);
                oTable.fnUpdate('<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a></a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>', nRow, 5, false);
                oTable.fnDraw();
            }
			
			
			         
            oTable = $('#table_common').dataTable({
                "aLengthMenu": [
                    [-1,5, 15, 20],
                    ["全部",'5条', '15条', '20条'] 
                ],
                "iDisplayLength": -1,
				"serverSide":true,
				//"aaSorting":[[0,'desc']],
				"bSort":false,
                "sPaginationType": "bootstrap",
				//"bStateSave": true, 
                "oLanguage": {
					"sSearch":"搜索",
                    "sLengthMenu": "每页显示 _MENU_ 记录",    
					"sEmptyTable":"没有数据",
					"sInfo": "当前数据为从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录",   
					"sInfoEmpty": "没有数据",   
					"sInfoFiltered" : "",
					"sInfoPostFix" : "",
					"sLoadingRecords":"",
					"sProcessing": "正在加载数据...", 
					"sZeroRecords": "没有检索到数据", 
                    "oPaginate": {   
						"sFirst": "首页",   
						"sPrevious": "上一页",   
						"sNext": "下一页",   
						"sLast": "尾页"  
					}   
                },
				"sAjaxSource":ajaxUrl,
				"sAjaxDataProp": "data",
				
				"aoColumns": [
					{"sTitle":'编号',"mDataProp": 'parentId'},
					{"sTitle":'分类名称',"mDataProp": 'catName'},
					{"sTitle":'分类排序',"mDataProp": 'catSort'},
					{"sTitle":'分类类型',"mDataProp": 'catType'},
					{"sTitle":'是否显示',"mDataProp": 'catFlag'},
					{"sTitle":'操作',"mDataProp": 'isShow'}
				],
                "aoColumnDefs": [{
                        'bSortable': false,
						'aTargets': ['_all']
                },
				{"aTargets":[1],"mRender":function(data,type,full){						
							return full['count']+data;
                    }},
				{"aTargets":[4],"mRender":function(data,type,full){
						if(data==1){
							return '<a href="#" class="catFlag btn btn-xs blue">显示</a>';
						}else{
							return '<a href="#" class="catFlag btn btn-xs default">隐藏</a>';
						}
                    },"sClass":'text-center',"sWidth":'5%'},
				{"aTargets":[5],"mRender":function(data,type,full){
					return '<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>';
                    },"sClass":'text-center',"sWidth":'5%'},
					
				],
				"fnCreatedRow":function(nRow,aData,iDataIndex){
					$('td:eq(0)',nRow).html(iDataIndex+1);//为第一个单元格增加序号
				}				
            });

            jQuery('#table_common_wrapper .dataTables_filter input').addClass("form-control input-medium input-inline"); // modify table search input
            jQuery('#table_common_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
            jQuery('#table_common_wrapper .dataTables_length select').select2({
                showSearchInput : false 
            }); 
			
			var nEditing = null;

			
			$('#table_common_new').click(function (e) {
                e.preventDefault();
				if (nEditing !== null) {
                    layer.confirm('确定不保存数据添加新行？',function(index){
						if($(nEditing).find("a[data-mode='new']").length>0){	
							oTable.fnDeleteRow(nEditing);	
						}else{
							restoreRow(oTable, nEditing);
						}
						var aiNew = oTable.fnAddData({"parentId":'',"catName":'', "catSort":'',"catType":'',"catFlag":'',
							"isShow":'<a class="edit btn btn-xs green" href="" name="Save"><i class="fa fa-check"></i> 保存</a></a><a class="cancel btn btn-xs default" data-mode="new" href=""><i class="fa fa-times"></i> 取消</a>'					
						});
						var nRow = oTable.fnGetNodes(aiNew[0]);
						editRow(oTable, nRow,"data-mode='new'");
						nEditing = nRow;
						layer.close(index);
					});
                }else{
					var aiNew = oTable.fnAddData({"parentId":'',"catName":'', "catSort":'',"catType":'',"catFlag":'',
						"isShow":'<a class="edit btn btn-xs green" href="" name="Save"><i class="fa fa-check"></i> 保存</a></a><a class="cancel btn btn-xs default" data-mode="new" href=""><i class="fa fa-times"></i> 取消</a>'					
					});
					var nRow = oTable.fnGetNodes(aiNew[0]);
					editRow(oTable, nRow,"data-mode='new'");
					nEditing = nRow;
				}    
            });
			
			//状态
			$('#table_common a.catFlag').live('click', function (e) {
                e.preventDefault();
                var nRow = $(this).parents('tr')[0];
				var aData = oTable.fnGetData(nRow);
				var catFlag = aData['catFlag']==1?0:1;
				$.post(ajaxUrl,{catId:aData['catId'],catFlag:catFlag,ajax:'catFlag'},function(data){
					if(data){
						layer.msg('分类状态修改成功！',{icon: 1,time: 2000});
						oTable.fnUpdate(catFlag, nRow,4, false);
						oTable.fnDraw();
					}else{
						layer.msg('分类状态未修改！',{icon: 2,time: 2000});
						return;
					}
			   });
            });
			
			//删除
            $('#table_common a.delete').live('click', function (e) {
				e.preventDefault();
				var nRow = $(this).parents('tr')[0];
				var aData = oTable.fnGetData(nRow);
				layer.confirm('确定删除该分类？',function(index){
					$.post(ajaxUrl,{catId:aData['catId'],ajax:'delArticleCats'},function(data){
						if(data==="other"){
							layer.msg('该分类存在子类不能删除！',{icon: 2,time: 2000});
							return;
						}
						if(data){
							layer.msg('分类删除成功！',{icon: 1,time: 2000});
							oTable.fnDeleteRow(nRow);
							
						}else{
							layer.msg('分类删除失败！',{icon: 1,time: 2000});
							return;
						}
				   });					
				});	
                
            });

            $('#table_common a.cancel').live('click', function (e) {
                e.preventDefault();
				var nRow = $(this).parents('tr')[0];
                if ($(this).attr("data-mode") == "new") {
                    
                    oTable.fnDeleteRow(nRow);
                } else {
                    restoreRow(oTable, nRow);
                    //nEditing = null;
                }
				nEditing = null;
            });

            $('#table_common a.edit').live('click', function (e) {
                e.preventDefault();
                var nRow = $(this).parents('tr')[0];
                if (nEditing !== null && nEditing != nRow) {
                    layer.confirm('确定不保存数据编辑新行？',function(index){
						if($(nEditing).find("a[data-mode='new']").length>0){	
							oTable.fnDeleteRow(nEditing);	
						}else{
							restoreRow(oTable, nEditing);
						}
						editRow(oTable, nRow);
						nEditing = nRow;
						layer.close(index);
					});
                } else if (nEditing == nRow && this.name == "Save") {
                    /* Editing this row and want to save it */
                    saveRow(oTable, nEditing);
					
					var aData = oTable.fnGetData(nRow);
					if(aData['catId']){
						aData['ajax']="editArticleCats";
					}else{
						aData['ajax']="addArticleCats";
					}
					//alert(aData);
					$.ajax({
						url: ajaxUrl,
						type: 'POST',
						dataType: 'json',
						data: aData,
						success : function(data) {
							if(data.status=='1'){
								layer.msg(data.info, 
									{icon: 1,time: 2000},
									function(){
									nEditing = null;
									oTable.fnReloadAjax();
									}
								);   	
							}else{
								layer.msg(data.info, 
									{icon: 2,time: 2000}
								);   
								return;
							}
						}
					});

                } else {
                    /* No edit in progress - let's start one */
                    editRow(oTable, nRow);
                    nEditing = nRow;
                }
            });
        }

    };

}();